<script lang="jsx">
  import { defineComponent, ref, computed } from 'vue'
  import customEditor from './ckeditor'
  import languageInit, { getLanguage } from './composables/language'

  export default defineComponent({
    name: 't-editor',
    emits: ['update:modelValue'],
    props: {
      modelValue: {
        type: String,
        default: ''
      },
      config: {
        type: Object,
        default: () => ({})
      },
      contentStyle: {
        type: Object,
        default: () => ({})
      },
      upload: {
        type: Function,
        default: null
      }
    },
    setup(props, { emit }) {
      const editorContext = ref()
      const onEditorReady = (editor) => {
        editor.upload = props.upload
        editorContext.value = editor

        // 禁用 stickyPanel，避免 有滚动条时 编辑器工具栏 位置移动到最顶部
        editor.ui.view.stickyPanel.unbind('isActive')
        editor.ui.view.stickyPanel.isActive = false
      }
      const content = computed({
        get() {
          return props.modelValue
        },
        set(val) {
          emit('update:modelValue', val)
        }
      })
      const language = getLanguage(props.config.language)
      const ckeditorComponent = languageInit(language)

      const attrs = {
        editor: customEditor(language),
        config: props.config,
        onReady: onEditorReady
      }

      const renderEditor = () => <div class="t-editor">
        <ckeditorComponent
          { ...attrs }
          v-model={content.value}
        />
      </div>

      return {
        renderEditor,
        editor: editorContext // ckeditor instance
      }
    },
    render() {
      return this.renderEditor()
    }
  })
</script>

<style lang="less">
  .ck-content {
    // 避免 源代码模式切换时 边框 导致 高度不一致
    box-sizing: border-box;

    // 默认 左对齐
    .table {
      float: left;

      & + * {
        clear: both;
      }

      table {
        td, th {
          padding: 0;
        }
      }
    }
  }
</style>
<style lang="less" scoped>
  .t-editor {
    height: v-bind('contentStyle.height');

    // 编辑器 内容区域 高度
    :deep(.ck-editor) {
      display: flex;
      flex-direction: column;
      height: 100%;
      min-height: v-bind('contentStyle.minHeight');
      max-height: v-bind('contentStyle.maxHeight');

      .ck-editor__main {
        flex: 1;
        height: 0;
        display: flex;
        flex-direction: column;
      }

      .ck-content,
      .ck-source-editing-area,
      .ck-source-editing-area::after {
        flex: 1;
        height: 0;
      }

      .ck-source-editing-area {
        &::after,
        textarea {
          overflow: auto;
        }
      }
    }
  }
</style>
